#include <iostream>
#include "LOG.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
using namespace std;




void Usege(string argv)
{
    cout << argv << " + sever_ip + sever_port" << endl;
}

int main(int args, char *argv[])
{
    //./socketclient + severip + severport
    if (args != 3)
    {
        Usege(argv[0]);
        exit(1);
    }
    string severip = argv[1];
    uint16_t severport = stoi(argv[2]);

    //1.创建socket
    int socketfd = socket(AF_INET,SOCK_DGRAM,0);
    if(socketfd < 0)
    {
        LOG(FATAL,"socketfd file:%s",strerror(errno));
        exit(2);
    }
    //clinet不用显式的bind，填ip和port，因为防止client port冲突
    //直接接收

    //构建目标主机的信息
    struct sockaddr_in sever;
    bzero(&sever,sizeof(sever));

    sever.sin_family = AF_INET;
    sever.sin_port = htons(severport);
    sever.sin_addr.s_addr = inet_addr(severip.c_str());

    string message;
    //直接通信
    while(1)
    {
        cout << "Please Enter a message: ";
        getline(cin,message);
        sendto(socketfd,message.c_str(),message.size(),0,(struct sockaddr*)&sever,sizeof(sever));

        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t n = recvfrom(socketfd,buffer,sizeof(buffer),0,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "server echo# " << buffer << std::endl;
        }
    }
}